import { handleActions } from 'redux-actions'

const init = {
	list: [],
	fieldMap: [],
	waitloadProfileTemplateList: []
}

export default handleActions({
  'reset profile template': (state) => ({
    ...state,
    ...init
  }),
	'fetch profile templates': (state, { payload }) => {
		const{ profileTemplateVOs=[] } = payload
		return {
			...state,
			list: profileTemplateVOs
		}
	},
	'fetch profile template fields': (state, { payload }) => {
		const { profileFieldVOs } = payload
		return {
			...state,
			fieldMap: profileFieldVOs,
			reorder: false
		}
	},
	'add profile template': (state, { payload }) => {
		return {
			...state,
			waitloadProfileTemplateList: [
				...state.waitloadProfileTemplateList,
				payload
			]
		}
	},
	'fetch single profile template': (state, { payload }) => {
		const { profileTemplateId } = payload
		return {
			...state,
			waitloadProfileTemplateList: state.waitloadProfileTemplateList.filter(item => item.profileTemplateId !== profileTemplateId),
			list: [
				...state.list,
				payload
			]
		}
	},
	'delete profile template': (state, { payload }) => {
		const profileTemplateId = payload
		return {
			...state,
			list: state.list.filter(item => item.profileTemplateId !== profileTemplateId)
		}
	},
	'reorder profile field': (state, { payload }) => ({
		...state,
		reorder: true
	}),
	'sort profile field': (state, { payload }) => {
		const { containerId, from, to } = payload
		const list = state.fieldMap;
		if (from < to) {
			return {
				...state,
				fieldMap: [
          ...list.slice(0, from),
          ...list[to],
          ...list.slice(from+1, to+1),
          list[from],
          ...list.slice(to+1)
        ]
			}
		} else {
			return {
				...state,
				fieldMap: [
          ...list.slice(0, to),
          list[from],
          ...list.slice(to, from),
          ...list.slice(from+1)
        ]
			}
		}
	},
	'add profile field': (state, { payload }) => {
		const { profileTemplateId } = payload
		return {
			...state,
			fieldMap: [...state.fieldMap, payload]
		}
	},
  'update profile field': (state, {payload}) => {
    const { profileFieldId, ...others } = payload;

    return {
      ...state,
      fieldMap: state.fieldMap.map((item) => {
        return item.profileFieldId === profileFieldId 
          ? {...item, ...payload} : item
      })
    }
    return state
  },
  'update profile field core': (state, {payload}) => {
    const { profileFieldId, ...others } = payload;

    return {
      ...state,
      fieldMap: state.fieldMap.map((item) => {
        return item.referenceName === payload.referenceName
          ? {...item, ...payload} : item
      })
    }
    return state
  },
  'delete profile field': (state, {payload}) => {
    const { profileTemplateId, profileFieldId } = payload
    return {
      ...state,
      fieldMap: state.fieldMap.filter(field => field.profileFieldId != profileFieldId)
    }
  }
}, init)
